package org.come.until;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Iterator;
import java.io.IOException;
import java.awt.image.ImageFilter;
import java.awt.image.BufferedImage;
import java.awt.image.ImageProducer;
import java.awt.image.FilteredImageSource;
import java.awt.Toolkit;
import java.awt.image.CropImageFilter;
import javax.imageio.ImageIO;
import java.io.File;
import java.awt.Image;
import java.util.List;
import java.lang.ref.SoftReference;
import org.come.bean.HeadImgBean;
import org.come.bean.ImgZoom;

import com.updateNew.MyIsif;

import javax.swing.ImageIcon;
import java.util.Map;

// 自定义LRU缓存实现
class LRUCache<K, V> extends LinkedHashMap<K, V> {
    private final int maxSize;

    public LRUCache(int maxSize) {
        // accessOrder设为true，表示按访问顺序维护链表
        super(16, 0.75f, true);
        this.maxSize = maxSize;
    }

    // 当缓存大小超过最大值时，移除最老的条目
    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > maxSize;
    }
}

public class CutButtonImage
{
    // 使用LRU缓存替代HashMap，限制缓存大小
    static Map<String, ImageIcon[]> img2 = new LRUCache<>(200); // 限制200个条目
    static Map<String, ImgZoom> img3 = new LRUCache<>(100);     // 限制100个条目
    static Map<String, HeadImgBean> img4 = new LRUCache<>(100); // 限制100个条目
    public static ImageIcon JT;
    // 对于SoftReference缓存，仍然使用HashMap，但增加清理机制
    public static Map<String, SoftReference<ImageIcon>> img = new LRUCache<>(300);
    private static List<String> headNulls = new ArrayList<>();

    // 定期清理SoftReference中已被回收的条目
    public static void cleanSoftReferenceCache() {
        Iterator<Map.Entry<String, SoftReference<ImageIcon>>> iterator = img.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, SoftReference<ImageIcon>> entry = iterator.next();
            if (entry.getValue() == null || entry.getValue().get() == null) {
                iterator.remove();
            }
        }
    }

    // 清理所有缓存
    public static void clearAllCache() {
        img2.clear();
        img3.clear();
        img4.clear();
        img.clear();
        headNulls.clear();
    }

    // 清理特定图像缓存
    public static void clearImageCache(String imagePath) {
        img2.remove(imagePath);
        img3.remove(imagePath);
        img4.remove(imagePath);
        img.remove(imagePath);
    }

    public static Image cut(final String srcImageFile, final int path) throws Exception {
        final BufferedImage src = ImageIO.read(new File(srcImageFile));
        final int destWidth = src.getWidth();
        final int destHeight = src.getHeight() / 3;
        for (int i = 0; i < 3; ++i) {
            if (i == path) {
                final ImageFilter cropFilter = new CropImageFilter(0, i * destHeight, destWidth, destHeight);
                final Image img = Toolkit.getDefaultToolkit().createImage((ImageProducer)new FilteredImageSource(src.getSource(), cropFilter));
                return img;
            }
        }
        return null;
    }

    public static ImageIcon[] cuts(final String srcImageFile) throws Exception {
        if (img2.get(srcImageFile) != null)
            return img2.get(srcImageFile);
        ImageIcon[] icons = new ImageIcon[3];
        File file = new File(srcImageFile);
        if (!file.exists()) {
            System.out.println("没素材:" + srcImageFile);
            icons[0]=getJT();
            icons[1]=getJT();
            icons[2]=getJT();
            return icons;
        }
        String[]vs=srcImageFile.split("/");
        boolean k=false;
        if (vs.length>=3&&(vs[2].equals("14.png")||vs[2].equals("13.png")||vs[2].equals("S412.png")||vs[2].equals("S413.png")))
            k=true;
        BufferedImage src = ImageIO.read(file);
        if (srcImageFile.contains("青龙")||srcImageFile.contains("玄武")||srcImageFile.contains("朱雀")||srcImageFile.contains("白虎")||srcImageFile.contains("中天"))
            k=true;
        if (vs.length>=3&&vs[2]!=null)
            if (vs[2].equals("14.png")||vs[2].equals("13.png")||vs[2].equals("S412.png")||vs[2].equals("S413.png"))
                k=true;
        if (srcImageFile.equals("inkImg/Client/无加号待解锁格.png")||srcImageFile.equals("inkImg/Client/待升级后解锁.png")||srcImageFile.equals("inkImg/Client/加号.png")||
                srcImageFile.equals("inkImg/Client/守护石.png")||srcImageFile.equals("inkImg/Client/守护石圆圈带未点亮守护石.png")||srcImageFile.equals("inkImg/Client/守护石圆圈带守护石.png")
        ){
            k=true;
        }
        // BufferedImage src = ImageIO.read(file);
        if (k){
            int destWidth = src.getWidth();
            int destHeight = src.getHeight() ;
            for (int i=0;i<3;i++){
                ImageFilter cropFilter = new CropImageFilter(0, i * destHeight, destWidth, destHeight);
                icons[i] = new ImageIcon(Toolkit.getDefaultToolkit().createImage(
                        new FilteredImageSource(src.getSource(), cropFilter)));
            }
            if ( srcImageFile.equals("inkImg/Client/守护石.png")){
                String imagePath = "inkImg/Client/守护石.png";  // Replace with the actual path to your image
                File imageFile = new File(imagePath);
                BufferedImage originalImage = ImageIO.read(imageFile);
                int maxSize = Math.max(originalImage.getWidth(), originalImage.getHeight());
                int scaledWidth = originalImage.getWidth() * 45 / maxSize;  // Adjust 50 to your desired size
                int scaledHeight = originalImage.getHeight() * 45 / maxSize; // Adjust 50 to your desired size
                Image scaledImage = originalImage.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_SMOOTH);
                icons[0]=new ImageIcon(scaledImage);
            }
            icons[2]=icons[0];
            icons[1]=icons[0];
            img2.put(srcImageFile, icons); // 也会受到LRU限制
            return icons;
        }

        int destWidth = src.getWidth();
        int destHeight = src.getHeight() / 3;
        for (int i = 0; i < 3; i++) {
            ImageFilter cropFilter = new CropImageFilter(0, i * destHeight, destWidth, destHeight);
            icons[i] = new ImageIcon(Toolkit.getDefaultToolkit().createImage(
                    new FilteredImageSource(src.getSource(), cropFilter)));
        }
        img2.put(srcImageFile, icons); // 也会受到LRU限制
        return icons;
    }
    public static ImageIcon size(String path,int w,int h){
        ImageIcon image=null;
        File imageFile = new File(path);
        BufferedImage originalImage = null;
        try {
            originalImage = ImageIO.read(imageFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        int maxSize = Math.max(originalImage.getWidth(), originalImage.getHeight());
        int scaledWidth = originalImage.getWidth() * w / maxSize;  // Adjust 50 to your desired size
        int scaledHeight = originalImage.getHeight() * h / maxSize; // Adjust 50 to your desired size
        Image scaledImage = originalImage.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_SMOOTH);
        image=new ImageIcon(scaledImage);
        return image;
    }
    public static ImageIcon[] cutsXy(final String srcImageFile) throws Exception {
        if (CutButtonImage.img2.get(srcImageFile) != null) {
            return (ImageIcon[])CutButtonImage.img2.get(srcImageFile);
        }
        final ImageIcon[] icons = new ImageIcon[3];
        final File file = new File(srcImageFile);
        if (!file.exists()) {
            System.out.println("没素材:" + srcImageFile);
            icons[0] = getJT();
            icons[1] = getJT();
            icons[2] = getJT();
            return icons;
        }
        final BufferedImage src = ImageIO.read(file);
        final int destWidth = src.getWidth();
        final int destHeight = src.getHeight() ;
        for (int i = 0; i < 3; ++i) {
            final ImageFilter cropFilter = new CropImageFilter(0, i * destHeight, destWidth, destHeight);
            icons[i] = new ImageIcon(Toolkit.getDefaultToolkit().createImage((ImageProducer)new FilteredImageSource(src.getSource(), cropFilter)));
        }
        CutButtonImage.img2.put(srcImageFile, icons);
        return icons;
    }

    public static ImageIcon[] cutsNew(final String srcImageFile) throws Exception {
        if (CutButtonImage.img2.get(srcImageFile) != null) {
            return (ImageIcon[])CutButtonImage.img2.get(srcImageFile);
        }
        final ImageIcon[] icons = new ImageIcon[3];
        final File file = new File(srcImageFile);
        if (!file.exists()) {
            System.out.println("没素材:" + srcImageFile);
            icons[0] = getJT();
            icons[1] = getJT();
            icons[2] = getJT();
            return icons;
        }
        final BufferedImage src = ImageIO.read(file);
        final int destWidth = src.getWidth();
        final int destHeight = src.getHeight() / 4;
        for (int i = 0; i < 3; ++i) {
            final ImageFilter cropFilter = new CropImageFilter(0, i * destHeight, destWidth, destHeight);
            icons[i] = new ImageIcon(Toolkit.getDefaultToolkit().createImage((ImageProducer)new FilteredImageSource(src.getSource(), cropFilter)));
        }
        CutButtonImage.img2.put(srcImageFile, icons);
        return icons;
    }

    public static ImgZoom cuts(final String srcImageFile, final int w, final int h, final boolean l) {
        if (CutButtonImage.img3.get(srcImageFile) != null) {
            return new ImgZoom((ImgZoom)CutButtonImage.img3.get(srcImageFile));
        }
        final ImgZoom zoom = new ImgZoom();
        final Image[] icons = new Image[9];
        try {
            final BufferedImage src = ImageIO.read(new File(srcImageFile));
            zoom.setMiddlew(src.getWidth() - 2 * w);
            zoom.setMiddleh(src.getHeight() - 2 * h);
            zoom.setEdgew(w);
            zoom.setEdgeh(h);
            zoom.setImgs(icons);
            final BufferedImage image1 = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
            drawImg(image1, src, 0, 0);
            icons[0] = image1;
            final BufferedImage image2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
            drawImg(image2, src, w + zoom.getMiddlew(), 0);
            icons[1] = image2;
            final BufferedImage image3 = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
            drawImg(image3, src, 0, h + zoom.getMiddleh());
            icons[2] = image3;
            final BufferedImage image4 = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
            drawImg(image4, src, w + zoom.getMiddlew(), h + zoom.getMiddleh());
            icons[3] = image4;
            final BufferedImage image5 = new BufferedImage(w, zoom.getMiddleh(), BufferedImage.TYPE_INT_ARGB);
            drawImg(image5, src, 0, h);
            icons[4] = image5;
            final BufferedImage image6 = new BufferedImage(w, zoom.getMiddleh(), BufferedImage.TYPE_INT_ARGB);
            drawImg(image6, src, w + zoom.getMiddlew(), h);
            icons[5] = image6;
            final BufferedImage image7 = new BufferedImage(zoom.getMiddlew(), h, BufferedImage.TYPE_INT_ARGB);
            drawImg(image7, src, w, 0);
            icons[6] = image7;
            final BufferedImage image8 = new BufferedImage(zoom.getMiddlew(), h, BufferedImage.TYPE_INT_ARGB);
            drawImg(image8, src, w, h + zoom.getMiddleh());
            icons[7] = image8;
            if (l) {
                final BufferedImage image9 = new BufferedImage(zoom.getMiddlew(), zoom.getMiddleh(), BufferedImage.TYPE_INT_ARGB);
                drawImg(image9, src, w, h);
                icons[8] = image9;
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        CutButtonImage.img3.put(srcImageFile, zoom);
        return zoom;
    }

    public static void drawImg(final BufferedImage img, final BufferedImage src, final int w, final int h) {
        int maxw = w;
        int maxh = h;
        maxw += img.getWidth();
        maxh += img.getHeight();
        if (maxw > src.getWidth()) {
            maxw = src.getWidth();
        }
        if (maxh > src.getHeight()) {
            maxh = src.getHeight();
        }
        for (int i = w; i < maxw; ++i) {
            for (int j = h; j < maxh; ++j) {
                img.setRGB(i - w, j - h, src.getRGB(i, j));
            }
        }
    }

    public static ImageIcon getJT() {
        if (CutButtonImage.JT == null) {
            CutButtonImage.JT = new ImageIcon("inkImg/hongmu/2/小地图红点0000.png");
        }
        return CutButtonImage.JT;
    }

    public static ImageIcon getImage(final String path, final int w, final int h) {
        if (w == -1) {
            SoftReference<ImageIcon> Simg = (SoftReference<ImageIcon>)CutButtonImage.img.get(path);
            if (Simg == null || Simg.get() == null) {
                ImageIcon imgp = new ImageIcon(path);
                if (imgp.getIconHeight() == -1) {
                    if (CutButtonImage.JT == null) {
                        CutButtonImage.JT = new ImageIcon("inkImg/hongmu/2/小地图红点0000.png");
                    }
                    imgp = CutButtonImage.JT;
                }
                Simg = (SoftReference<ImageIcon>)new SoftReference(imgp);
                CutButtonImage.img.put(path, Simg);
            }
            return (ImageIcon)Simg.get();
        }
        final String value = w + "" + h + path;
        SoftReference<ImageIcon> Simg2 = (SoftReference<ImageIcon>)CutButtonImage.img.get(value);
        if (Simg2 == null || Simg2.get() == null) {
            ImageIcon imgp2 = getImage(path, -1, -1);
            if (imgp2 == CutButtonImage.JT) {
                return CutButtonImage.JT;
            }
            if (imgp2.getIconHeight() == h && imgp2.getIconWidth() == w) {
                return imgp2;
            }
            imgp2 = new ImageIcon(imgp2.getImage().getScaledInstance(w, h, Image.SCALE_SMOOTH));
            Simg2 = (SoftReference<ImageIcon>)new SoftReference(imgp2);
            CutButtonImage.img.put(value, Simg2);
        }
        return (ImageIcon)Simg2.get();
    }

    public static ImageIcon getCBG(final int type, final String path, final int w, final int h) {
        if (type == 2) {
            return getImage("img/item/8.png", w, h);
        }
        if (type == 3 || type == 5) {
            return getImage("img/item/" + path + ".png", w, h);
        }
        if (type == 4) {
            ImageIcon pet = getImage("img/newHead/p" + path + ".png", w, h);
            if (pet == CutButtonImage.JT) {
                pet = getImage("inkImg/hongmu/2/101_png.xy2uiimg.pet_def.png", w, h);
            }

            return pet;
        }
        if (type == 6) {
            return getImage("inkImg/old/lingbao/" + path + ".png", w, h);
        }
        if (CutButtonImage.JT == null) {
            CutButtonImage.JT = new ImageIcon("inkImg/hongmu/2/小地图红点0000.png");
        }
        return CutButtonImage.JT;
    }

    public static ImageIcon getGemstoneIcon(final String path, final int w, final int h) {
        return getImage("img/item/" + path + ".png", w, h);
    }

    public static ImageIcon TYC(final String type) {
        if(MyIsif.getStyle().equals("水墨UI")) {
            if ("毒".equals(type)) {
                return getImage("inkImg/old/1/66.png", -1, -1);
            } else if ("三尸虫".equals(type)) {
                return getImage("inkImg/old/1/63.png", -1, -1);
            } else if ("震慑".equals(type) || "盘丝".equals(type) || "遗忘".equals(type) || "魅惑".equals(type)) {
                return getImage("inkImg/old/1/64.png", -1, -1);
            } else if ("风".equals(type) || "雷".equals(type) || "水".equals(type) || "火".equals(type)) {
                return getImage("inkImg/old/1/67.png", -1, -1);
            } else {
                return getImage("inkImg/old/1/65.png", -1, -1);
            }
        }else {
            if (type.equals("毒")) {
                return getImage("img/soaringSkill/天演策-女人w170,h310.png", -1, -1);
            }
            if (type.equals("三尸虫")) {
                return getImage("img/soaringSkill/天演策-鬼w170,h310.png", -1, -1);
            }
            if (!type.equals("震慑") && !type.equals("盘丝") && !type.equals("遗忘") && !type.equals("魅惑")) {
                return (!type.equals("风") && !type.equals("雷") && !type.equals("水") && !type.equals("火")) ? getImage("img/soaringSkill/天演策-男人w170,h310.png", -1, -1) : getImage("img/soaringSkill/天演策-仙w170,h310.png", -1, -1);
            }
            return getImage("img/soaringSkill/天演策-魔w170,h310.png", -1, -1);
        }
    }

    public static ImageIcon TYCSkill(final int id) {
        return getImage("inkImg/hongmu/soaringSkill/40×40/" + id + ".png", -1, -1);
    }

    public static ImageIcon LxSkill(final int id) {
        return getImage("inkImg/old/skill/wxs_" + id + ".png", -1, -1);
    }

    public static ImageIcon shimenskll(final int id) {
        return getImage("inkImg/old/skill/wxs_" + id + ".png", -1, -1);
    }

    public static HeadImgBean getNPCHeadImg(final String imgPath) {
        if (CutButtonImage.headNulls.contains(imgPath)) {
            return null;
        }
        HeadImgBean imgBean = (HeadImgBean)CutButtonImage.img4.get(imgPath);
        if (imgBean != null) {
            imgBean.setNum(4);
            return imgBean;
        }
        ImageIcon icon = new ImageIcon("img/head/N" + imgPath + ".png");
        if (icon.getIconHeight() == -1) {
            icon = new ImageIcon("img/head/N600000.png");
        }
        if (icon.getIconHeight() != -1) {
            imgBean = new HeadImgBean(4, icon);
            CutButtonImage.img4.put(imgPath, imgBean);
            return imgBean;
        }
        CutButtonImage.headNulls.add(imgPath);
        return null;
    }

    public static void removeNPCHeadImg() {
        final Iterator<String> it = CutButtonImage.img4.keySet().iterator();
        while (it.hasNext()) {
            final String key = (String)it.next();
            final HeadImgBean imgBean = (HeadImgBean)CutButtonImage.img4.get(key);
            if (imgBean.is()) {
                it.remove();
            }
        }
    }

    // 原有的静态初始化代码可以删除，因为我们已经在字段声明时初始化了
    // static {
    //     img2 = (Map<String, ImageIcon[]>)new HashMap();
    //     img3 = (Map<String, ImgZoom>)new HashMap();
    //     img4 = (Map<String, HeadImgBean>)new HashMap();
    //     img = (Map<String, SoftReference<ImageIcon>>)new HashMap();
    //     headNulls = (List<String>)new ArrayList();
    // }
}
